package leetcode

/*
 * @lc app=leetcode.cn id=54 lang=golang
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
func spiralOrder(matrix [][]int) []int {
	rows, cols := len(matrix), len(matrix[0])
	n := rows * cols
	ret := make([]int, n)
	for i, c := 0, 0; i < n; c++ {
		right, bottom := cols-1-c, rows-1-c
		for j := c; j <= right; j++ {
			ret[i] = matrix[c][j]
			i++
		}
		for j := c + 1; j <= bottom; j++ {
			ret[i] = matrix[j][right]
			i++
		}
		if c < bottom && c < right {
			for j := cols - 2 - c; c <= j; j-- {
				ret[i] = matrix[bottom][j]
				i++
			}
			for j := rows - 2 - c; c < j; j-- {
				ret[i] = matrix[j][c]
				i++
			}
		}
	}
	return ret
}

// @lc code=end
